import request from '../../utils/request'
import { uploadFileToQiniu } from '../../utils/qiniuUpload'


// pages/index/index.js
Page({
  data: {
    keyword: "",
    images: {
      mainImage: '',
      subImages: [] // 存放额外副图的数组
    },
    commodityId: 0,
    mainImageKey: "",
    textContent: ""
  },

  onInput(e) {
    this.setData({ textContent: e.detail.value })
  },

  // 监听输入（实时更新 keyword）
  handleInput(e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  // 触发搜索（点击按钮或回车）
  handleSearch() {
    const keyword = this.data.keyword.trim();
    if (!keyword) {
      wx.showToast({ title: "关键词不能为空", icon: "none" });
      return;
    }
 
    request({
      url: 'commodities/random',
      method: 'GET',
      data: {
        name: keyword
      }
    }).then(res => {
      const data = res.data
      this.setData({
        commodityId: data.commodityId,
        mainImageKey: data.image.key,
        "images.mainImage": data.image.url
      })
    })
    .catch(err => {
      console.log(err)
      this.setData({
        "images.mainImage": ""
      })
      wx.showToast({
        title: err.message || '请求失败',
        icon: 'none',
        duration: 3000
      });
    })
  },



  
  // 选择主图
  chooseMainImage() {
    // 如果已有主图，不允许再次上传
    if (this.data.images?.mainImage || !this.data.commodityId) {
      // wx.showToast({
      //   title: '主图已上传',
      //   icon: 'none'
      // });
      return;
    }


    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if (!res.tempFiles || res.tempFiles.length === 0) return;

        const mainImage = res.tempFiles[0].tempFilePath;
        const newSubImages = res.tempFiles.slice(1).map(item => item.tempFilePath);

        // 取已有 subImages，做合并
        const currentSubImages = this.data.images?.subImages || [];
        const mergedSubImages = currentSubImages.concat(newSubImages);

        this.setData({
          'images.mainImage': mainImage,
          'images.subImages': mergedSubImages
        });

        console.log('主图:', mainImage);
        console.log('副图:', mergedSubImages);
      }
    });
  },

  previewMainImage() {
    const { images } = this.data;
    if (!images.mainImage) return;
  
    wx.previewImage({
      current: images.mainImage, // 当前显示的图片（可以是数组中的某一张）
      urls: [images.mainImage]   // 所有可预览的图片列表
    });
  },

  // 添加更多副图
  addSubImage() {
    wx.chooseMedia({
      count: 9, // 每次最多选 9 张，用户可多次添加
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const currentSubImages = this.data.images?.subImages || [];

        // 提取新选中的图片路径
        const newSubImages = res.tempFiles.map(item => item.tempFilePath);

        // 合并副图
        const mergedSubImages = currentSubImages.concat(newSubImages);

        console.log('当前已有副图:', currentSubImages);
        console.log('新添加副图:', newSubImages);
        console.log('更新后副图:', mergedSubImages);

        // 更新数据
        this.setData({
          'images.subImages': mergedSubImages
        });
      }
    });
  },

  // 删除主图
  deleteMainImage() {
    this.setData({
      'images.mainImage': ''
    });
  },

  // 删除副图
  deleteSubImage(e) {
    const index = e.currentTarget.dataset.index;
    const newSubImages = this.data.images.subImages.filter((_, i) => i !== index);
    this.setData({
      'images.subImages': newSubImages
    });
  },

  // 处理上传
  async handleUpload() {
    const { images, mainImageKey } = this.data;
     // 检查主图是否上传
     if (!this.data.commodityId) {
      wx.showToast({
        title: '请搜索商品',
        icon: 'none'
      });
      return;
    }


    // 检查主图是否上传
    if (!images.mainImage) {
      wx.showToast({
        title: '请上传原图',
        icon: 'none'
      });
      return;
    }

    // 检查结果图是否上传
    if (!images.subImages) {
      wx.showToast({
        title: '请上传结果图',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '上传中...',
    });
    
    // 实际项目中这里应调用服务器接口
    try {
      // ✅ 上传主图
      // const mainRes = await uploadFileToQiniu(images.mainImage, 'ai-train-controlNet-source');

      // ✅ 上传所有副图
      const subResults = await Promise.all(
        images.subImages.map(img => uploadFileToQiniu(img, 'commodity'))
      );

      // ✅ 合并 key 返回
      const uploaded = [mainImageKey, ...subResults.map(item => item.key)];
      console.log('上传成功结果：', uploaded);
      
      await request({
        url: 'commodities',
        method: 'PUT',
        data: {
          commodityId: this.data.commodityId,
          imageKeyList: uploaded,
          textContent: this.data.textContent || ''   // 文本输入框绑定的内容
          // 标签选择绑定的内容
        }
      });
      wx.hideLoading();
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000 // 建议显式写时长，默认1500ms
      });
      
      // 1秒后再清空状态，避免 toast 被覆盖
      setTimeout(() => {
        this.setData({
          images: { mainImage: '', subImages: [] },
          textContent: '',
          commodityId: 0,
        });
      }, 1000);
    } catch (err) {
      console.error('上传失败：', err);
      wx.showToast({ title: '上传失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  }
});